package com.cloud.demo.common.web.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.cloud.demo.common.cache.cachekey.UserCacheKeyBuild;
import com.cloud.demo.common.enums.ResultEnum;
import com.cloud.demo.common.tool.JwtTool;
import com.cloud.demo.common.web.exception.SysException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String key = new UserCacheKeyBuild().getKey(token);
        String sale = stringRedisTemplate.opsForValue().get(key);
        if (sale==null) {
            throw new SysException(ResultEnum.NOT_LOGIN );
        }
        //redis 查 盐，如果没有没有登录 sys:user:login:(token)
        JWTVerifier build = JwtTool.verifier(sale);
        // 有盐 则查看token（jwt）有没被修改
        // token+盐==jwt 则匹配成成功  可后续匹配权限
        // 匹配不成功报错异常 signException ，

        return false;
    }
}
